<?php

require_once('./modules/blog/blogpost.inc');
require_once('./modules/tag.inc');

class EditPostRenderer extends Renderer
{
	private $_post;
	
	function pageLoad()
	{
		$postId = Util::safeGetPost('postId');
	
		$this->_post = new BlogPost();
		
		$this->_post->load($postId);
		
		switch( $this->action )
		{
			case "save":
				$this->savePost();
				break;
			case "":
			case "show":
			default:
				break;
		}
	}

	function isPermitted()
	{
		if ( isset($this->user) && $this->user->type >= 1)
			return true;
		else
			return false;
	}
	
	
	function savePost()
	{
		$title = Util::safeGetPost('txtTitle');
		$desc = Util::safeGetPost('txtDesc');
		$content = html_entity_decode(html_entity_decode(Util::safeGetPost('txtContent'),ENT_QUOTES),ENT_QUOTES);
		$tags = Tag::parseFreeText(Util::safeGetPost('txtTags'));		
		
		$result = $this->_post->update($title,$desc,$content,$tags);
				
		if($result)
		{
			//revoking the cached file, so the page will be reloaded.
			$cacheId = "post-id-".$this->_post->id;	
			$cache = new Cache();
			$cache->revoke($cacheId);
			header("Location: index.php?pg=edit_post&postId=".$this->_post->id."&status=success");
		}
		else
			header("Location: index.php?pg=edit_post&postId=".$this->_post->id."&status=failed");
	}

	function renderBreadcrumbs()
	{
		parent::renderBreadcrumbs();
		
		global $breadcrumbs;
		
		$breadcrumbs .= "&nbsp;&#187;&nbsp;Edit post";
	}
	
	function renderContent()
	{
		global $content;
		global $siteName;

		$content .= 
			"<script type=\"text/javascript\" src=\"./modules/ext/tiny_mce/tiny_mce.js\"></script>
			<script type=\"text/javascript\">
			tinyMCE.init({
				theme : \"advanced\",
				mode : \"textareas\",
				plugins : \"fullscreen,advimage,advlink,searchreplace,table,contextmenu,paste\",
				theme_advanced_buttons3_add : \"fullscreen,search,replace,tablecontrols,pastetext,pasteword,selectall\",
				fullscreen_new_window : true,
				fullscreen_settings : {
					theme_advanced_path_location : \"top\"
				},
				table_styles : \"Header 1=header1;Header 2=header2;Header 3=header3\",
				table_cell_styles : \"Header 1=header1;Header 2=header2;Header 3=header3;Table Cell=tableCel1\",
				table_row_styles : \"Header 1=header1;Header 2=header2;Header 3=header3;Table Row=tableRow1\",
				table_cell_limit : 100,
				table_row_limit : 5,
				table_col_limit : 5,
			   paste_auto_cleanup_on_paste : true,
				paste_preprocess : function(pl, o) {
					alert(o.content);
				},
				paste_postprocess : function(pl, o) {
					alert(o.node.innerHTML);
				}				
			});
			</script>
			<script>
				function addTag(tag)
				{						
					var val = $('#txtTags').val();
					var rgx = new RegExp('(?:^|,)'+tag+'(?:,|$)','i');
					if(rgx.test(val) == false)
					{
						if(val.length > 0 )
							val += ',';
						$('#txtTags').val(val + tag);
						
						markSelectedTags();
					}
				}
				
				function markSelectedTags()
				{
					var txt = $('#txtTags').val();
					$('.tagItem').each(
					function() {
						curr = $(this);
						var currTxt = curr.text();
						
						var rgx = new RegExp('(?:^|,)'+currTxt+'(?:,|$)','i');
						if(rgx.test(txt))
							curr.addClass('tagItemSelected');
						else
							curr.removeClass('tagItemSelected');
					});
				}
			</script>";
			
		$content .= 
		"<div class='headerPitch'>
			<p><h1>Edit post</h1></p>
		</div>";
		if( isset($GET_['status']) && $_GET['status'] == 'failed' )
			$content .= "<P/><label style='color:red;'>Failed to save post</label>";
		else if(isset($_GET['status']) && $_GET['status'] == "success")
			$content .= "<P/><label style='color:green;'>Post saved successfully</label>";		
		$content .="<div class='pageContentTitle'>
			<p></p>
		</div>
		<div class='pageContent'>
			<p>
			<form method='POST' action='index.php?pg=edit_post&postId=".$this->_post->id."&act=save'>
			<fieldset style='width:580px;padding:20px;'>
				<legend>Post details:</legend>
				Title: <input type='text' name='txtTitle' id='txtTitle' size='109' value='".$this->_post->title."'/><br />
				Description: <input type='text' name='txtDesc' id='txtDesc' size='109' value='".$this->_post->desc."'/><br />
				Content: <textarea style='width:550px;height:500px;' id='txtContent' name='txtContent'>".$this->_post->content."</textarea><br />
				Tags: <input type='text' name='txtTags' id='txtTags' size='109' value='";

				$isFirst = true;
				foreach($this->_post->tags as $tag)
				{
					if(!$isFirst)
						$content.= ",";
					$content .= $tag->tag;
					$isFirst = false;
				}
				
				$content .= "'/><br/><br/>
				<script>
					$('#txtTags').bind('keyup',markSelectedTags);
					$(document).ready(markSelectedTags);
				</script>
				<div id='tags'>";
		
		$tags = Tag::getAll();
		foreach($tags as $tagRow)
			$content .= "<span class='tagItem' onclick='addTag(\"".$tagRow['tag']."\");'>".$tagRow['tag']."</span>";
		
		$content.="</div><br/>
				<input type='submit' value='Save'/>";		
		$content .= "				</fieldset>
			</form>
			</p>
		</div>";
	}
}

$renderer = new EditPostRenderer();

?>
